<?php

namespace App\Repositories;

use App\Exceptions\BasicException;
use App\Enums\ErmEnum;
use DB;

class ErmRiskDeviceRepository
{
    /**
     * 获取风险类型
     *
     * @param $param
     * @return mixed
     * @throws BasicException
     */
    public function getRiskType()
    {
        $list = app('model_shumei_risk_type')->get()->toArray();
        $list = array_column($list, null, 'id');
        foreach ($list as $k => $v) {
            if ($v['pid'] > 0) {
                $list[$v['pid']]['children'][] = $v;
                unset($list[$k]);
            }
        }
        return array_values($list);
    }

    /**
     * 获取预警设备列表
     *
     * @param $param
     * @param $page
     * @param $perPage
     * @return mixed
     * @throws BasicException
     */
    public function getRiskDevice($params, $page, $perPage)
    {
        $model = app('model_shumei_rm_log')
            ->from(app('model_shumei_rm_log')->getTable() . ' as t1')
            ->leftJoin(DB::raw(app('model_user_data')->getTable() . " as t2"), "t1.user_id", "=", "t2.user_id");
        // ->leftJoin(DB::raw(app('model_shumei_risk_type')->getTable() . " as t3"), "t1.risk_type", "=", "t3.id");
        if (isset($params['user_code'])) {
            $model->where('t2.user_code', $params['user_code']);
        }
        if (isset($params['risk_type'])) {
            $riskTypeIds = app('model_shumei_risk_type')->where('pid', $params['risk_type'])->pluck('id')->toArray();
            if (!$riskTypeIds) {
                $riskTypeIds = [$params['risk_type']];
            }
            $model->whereIn('t1.risk_type', $riskTypeIds);
        }
        if (!empty($params['ip'])) {
            $model->where('t1.ip', $params['ip']);
        }
        $list = $model->select(
            't1.id',
            't1.device_id',
            't1.ip',
            't1.risk_type',
            't1.add_time',
            't1.reason',
            't2.user_code',
            't2.nickname',
        )
            ->where('risk_type', '>', 0)
            ->orderBy('t1.id', 'desc')
            ->paginate($perPage, ['*'], '', $page)
            ->toArray();

        $riskArr = app('model_shumei_risk_type')
            ->get()
            ->toArray();

        if ($riskArr) {
            $riskArr = array_column($riskArr, null, 'id');
        }
        $riskArr[0] = [
            'id' => 0,
            'pid' => 0,
            'name' => '正常',
        ];

        foreach ($list['data'] as $k => $v) {
            $list['data'][$k]['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
            $list['data'][$k]['risk_type_child_name'] = $riskArr[$v['risk_type']]['name'];
            $pid = $riskArr[$v['risk_type']]['pid'];
            $list['data'][$k]['risk_type_name'] = $riskArr[$pid]['name'];
        }
        return $list;
    }

    /**
     * 获取预警设备白名单列表
     *
     * @param $id
     * @return mixed
     * @throws BasicException
     */
    public function getWhiteList($params, $page, $perPage)
    {
        $model = app('model_shumei_risk_white_list')
            ->from(app('model_shumei_risk_white_list')->getTable() . ' as t1')
            ->leftJoin(DB::raw(app('model_user_data')->getTable() . " as t2"), "t1.user_id", "=", "t2.user_id");
        if (isset($params['user_code'])) {
            $model->where('t2.user_code', $params['user_code']);
        }
        if (!empty($params['device_id'])) {
            $model->where('t1.device_id', $params['device_id']);
        }
        if (!empty($params['operator_id'])) {
            $model->where('t1.operator_id', $params['operator_id']);
        }
        if (!empty($params['risk_type'])) {
            $model->where('t1.risk_type', $params['risk_type']);
        }
        if (!empty($params['start_add_time'])) {
            $model->where('t1.add_time', '>=', $params['start_add_time']);
        }
        if (!empty($params['end_add_time'])) {
            $model->where('t1.add_time', '<=', $params['end_add_time']);
        }
        $list = $model->select([
                't1.id',
                't1.device_id',
                't1.add_time',
                't1.risk_type',
                't1.operator_id',
                't2.user_code',
                't2.nickname',
            ])
            ->orderBy('t1.id', 'desc')
            ->paginate($perPage, ['*'], '', $page)
            ->toArray();

        $shumeiRiskTypeRes = app('model_shumei_risk_type')->get()->toArray();
        $shumeiRiskTypeMap = array_column($shumeiRiskTypeRes, null, 'id');
        foreach ($list['data'] as $k => $v) {
            $riskType = $v['risk_type'] ?? 0;
            $list['data'][$k]['risk_type'] = $shumeiRiskTypeMap[$riskType]['name'] ?? '';
        }

        return $list;
    }

    /**
     * 添加预警设备白名单
     *
     * @param array $param
     * @return mixed
     * @throws BasicException
     */
    public function addWhiteList($param)
    {
        $log = app('model_shumei_rm_log')->where('id', $param['id'])->first();
        if (!$log) {
            throw new BasicException(10001, '无效的预警设备');
        }
        // 添加到白名单
        $whiteList = app('model_shumei_risk_white_list')->where('device_id', $log->device_id)->first();
        if ($whiteList) {
            throw new BasicException(10001, '该设备已经在白名单中');
        }
        $whiteList = [
            'log_id' => $log->id,
            'device_id' => $log->device_id,
            'user_id' => $log->user_id,
            'risk_type' => $log->risk_type,
            'operator_id' => $param['operator_id'],
        ];
        app('redis')->sadd(ErmEnum::DEVICE_WHITE_LIST_KEY, $log->device_id);
        return app('model_shumei_risk_white_list')->insertGetId($whiteList);
    }

    /**
     * 删除预警设备白名单
     *
     * @param int $id
     * @return mixed
     * @throws BasicException
     */
    public function removeWhiteList($id)
    {
        $whiteList = app('model_shumei_risk_white_list')->where('id', $id)->first();
        if (!$whiteList) {
            throw new BasicException(10001, '无效的白名单');
        }
        app('redis')->srem(ErmEnum::DEVICE_WHITE_LIST_KEY, $whiteList->device_id);
        return app('model_shumei_risk_white_list')->where('id', $id)->delete();
    }
}
